<template>
  <ProTable
    ref="tableRef"
    :fetchListApi="_listLog"
    :columns="columns"
    row-key="alarmId"
  >
    <template #toolbars>
      <b-button icon="conf" @click="handleWarningOpen" code="alarmConfig:add"
        >告警配置</b-button
      >
    </template>
    <template #operation="{ record }">
      <b-button
        icon="edit"
        type="link"
        @click="onView(record)"
        v-if="record.handleState == 0"
        code="alarmLog:edit"
        >处理</b-button
      >
      <b-button
        icon="detail"
        type="link"
        @click="onView(record)"
        v-else
        code="alarmLog:query"
        >查看</b-button
      >
    </template>
  </ProTable>
  <FormModal :items="items" />
  <FormModalView :items="itemsView" />
</template>

<script setup lang="tsx">
import { computed, ref } from 'vue';
import { Tag } from 'ant-design-vue';
import { useRoute } from 'vue-router';
import { hasPermission } from '@/permission/utils';
import { ProFormProps } from '@/components/ProForm';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import { useFormModal } from '@/hooks/formModal';
import { listToEnum, listToOption } from '@/utils/utils';
import { fetchDictsOfType } from '@/api/dict';
import {
  addAlarmConfig,
  getAlarmConfig,
  getLog,
  listLog,
  upAlarmConfig,
  updateLog,
} from '@/api/notice';

const tableRef = ref();
const _listLog = async (params: any) => {
  const handleState =
    params.handleState == 'undefined' ? undefined : params.handleState;
  return listLog({
    ...params,
    handleState,
  });
};
const alarmDescEnum = {
  NTP对时不成功: 'NTP对时不成功',
  MQTT连接不成功: 'MQTT连接不成功',
  文件服务状态异常: '文件服务状态异常',
  自动定位服务状态异常: '自动定位服务状态异常',
};
const route = useRoute();
const onlineStatus = route.query.onlineStatus;
const handleState = route.query.handleState;
const handleStateEnum = {
  undefined: '全部',
  0: '待处理',
};

const sysYesNoOption = ref<Global.Option[]>([]);
const sysOnlineStatusEnum = ref<Record<string, any>>({});
const init = () => {
  fetchDictsOfType(['sys_yes_no', 'sys_on_line_status']).then((res: any) => {
    const { sys_yes_no, sys_on_line_status } = res.data;
    sysYesNoOption.value = listToOption(sys_yes_no, 'dictLabel', 'dictValue');
    sysOnlineStatusEnum.value = listToEnum(
      sys_on_line_status,
      'dictValue',
      'dictLabel',
    );
  });
};
init();

const columns = computed<ProTableProps['columns']>(() => [
  {
    title: '告警时间',
    dataIndex: 'alarmTime',
    isTime: true,
  },
  {
    title: '项目名称',
    dataIndex: 'projectName',
  },
  {
    title: '设备序列号',
    dataIndex: 'serialNo',
  },
  {
    title: '在线状态',
    dataIndex: 'onlineStatus',
    valueEnum: {
      ...sysOnlineStatusEnum.value,
    },
    customRender({ text }) {
      return (
        <Tag color={text == '0' ? 'error' : 'processing'}>
          {
            sysOnlineStatusEnum.value?.[
              text as keyof typeof sysOnlineStatusEnum.value
            ]
          }
        </Tag>
      );
    },
    defaultValue: onlineStatus,
  },
  {
    title: '告警类型',
    dataIndex: 'alarmDesc',
    valueEnum: {
      ...alarmDescEnum,
    },
  },
  {
    title: '处理状态',
    dataIndex: 'handleStateLabel',
    hideInSearch: true,
  },
  {
    title: '处理状态',
    dataIndex: 'handleState',
    hideInTable: true,
    valueEnum: {
      ...handleStateEnum,
    },
    defaultValue: handleState,
  },
  {
    title: '处理时间',
    dataIndex: 'updateTime',
    isTime: true,
  },
  {
    title: '处理人',
    dataIndex: 'handleBy',
    hideInSearch: true,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    fixed: 'right',
    width: 80,
  },
]);

const items = computed<ProFormProps['items']>(() => [
  {
    label: '设备离线告警-沉默周期',
    type: 'input',
    field: 'offlineConfig',
    rules: [{ required: true, message: '请输入沉默周期', trigger: 'blur' }],
    props: {
      placeholder: '24',
      addonAfter: '小时',
    },
  },
  {
    label: 'NTP对时不成功告警-沉默周期',
    type: 'input',
    field: 'ntpConfig',
    rules: [{ required: true, message: '请输入沉默周期', trigger: 'blur' }],
    props: {
      placeholder: '24',
      addonAfter: '小时',
    },
  },
  {
    label: 'MQTT连接不成功告警-沉默周期',
    type: 'input',
    field: 'mqttConfig',
    rules: [{ required: true, message: '请输入沉默周期', trigger: 'blur' }],
    props: {
      placeholder: '24',
      addonAfter: '小时',
    },
  },
  {
    label: '文件服务连接不成功告警-沉默周期',
    type: 'input',
    field: 'fileConfig',
    rules: [{ required: true, message: '请输入沉默周期', trigger: 'blur' }],
    props: {
      placeholder: '24',
      addonAfter: '小时',
    },
  },
  {
    label: 'gps服务连接不成功告警-沉默周期',
    type: 'input',
    field: 'gpsConfig',
    rules: [{ required: true, message: '请输入沉默周期', trigger: 'blur' }],
    props: {
      placeholder: '24',
      addonAfter: '小时',
    },
  },
]);
const { FormModal, open } = useFormModal({
  size: 'small',
  formProps: {
    labelCol: { span: 9 },
    wrapperCol: { span: 12 },
  },
});

const itemsView = computed<ProFormProps['items']>(() => [
  {
    label: '是否误报',
    type: 'radio',
    field: 'isFalseAlarm',
    rules: [{ required: true, message: '请选择是否误报', trigger: 'blur' }],
    props: {
      options: sysYesNoOption.value,
    },
  },
  {
    label: '处理结果',
    type: 'textarea',
    field: 'handleResult',
    rules: [{ required: true, message: '请输入处理结果', trigger: 'blur' }],
    props: {
      placeholder: '请输入处理结果最多100字',
      maxlength: 100,
    },
  },
  {
    label: '处理时间',
    type: 'input',
    field: 'updateTime',
    hide: (state) => !state.handleState,
  },
  {
    label: '处理人',
    type: 'input',
    field: 'handleBy',
    hide: (state) => !state.handleState,
  },
]);
const { FormModal: FormModalView, open: openView } = useFormModal({
  size: 'small',
});

const onView = async (record: any) => {
  const handleState = record.handleState;
  const alarmId = record.alarmId;
  let form = { alarmId };
  if (handleState != 0) {
    const res = await getLog(alarmId);
    form = res.data as any;
  }
  openView({
    title: handleState == 0 ? '处理' : '查看',
    modalType: handleState == 0 ? 'add' : 'disabled',
    hasEditPermission:
      handleState == 0
        ? hasPermission('alarmLog:edit')
        : hasPermission('alarmLog:query'),
    defaultValue: { ...form },
    serviceApi: async (params: any): Promise<any> => {
      await updateLog(params);
      tableRef.value.refresh();
    },
  });
};

const handleWarningOpen = async () => {
  let submitFlag = false;
  let warningData = {};
  const res = await getAlarmConfig();
  if (res.code == 200 && res.rows.length > 0) {
    warningData = res.rows[0];
    submitFlag = true;
  }
  open({
    title: '告警配置-预警终端',
    defaultValue: { ...warningData },
    serviceApi: async (params: any): Promise<any> => {
      if (submitFlag) {
        await upAlarmConfig(params);
      } else {
        await addAlarmConfig(params);
      }
    },
  });
};
</script>
